import datetime

import time

import sys
import subprocess

from utils.file_util import get_adb_path

adb_path = get_adb_path()

def get_current_app():
    return exec_adb(['shell', "dumpsys window | grep -E 'mCurrentFocus' |  awk '{split($0, a);print a[3]}' | cut -d '/' -f 1"]).strip()

def kill_app(package_name):
    exec_adb(['shell', 'am', 'force-stop', package_name])

def kill_current_app():
    current_app = get_current_app()
    if 'launcher' not in current_app:
        return exec_adb(['shell', 'am', 'force-stop', current_app])

def exec_python(cmds:list):
    return exec_cmd([sys.executable] + cmds)

def exec_adb(cmds:list):
    return exec_cmd([adb_path] + cmds)

def exec_cmd(cmds:list):
    ret = subprocess.run(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    str_ret = None
    try:
        if ret.returncode != 0:
            if "push" in cmds or "pull" in cmds:
                cmds = cmds[0:2]
            str_ret = ret.stderr
            print("exec " + str(cmds) + " failed. stdout \n" + str_ret)
        else:
            str_ret = ret.stdout
            print("exec " + str(cmds) + " succeed. stdout \n" + str_ret)
    except Exception as e:
        print(str(e))
    return str_ret

def exec_python_with_communicate(cmds:list) -> subprocess.Popen[bytes]:
    process = subprocess.Popen([sys.executable] + cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return process

def send_input(process:subprocess.Popen[bytes], input_text):
    str_ret = []
    print('run before: ', datetime.datetime.now())
    process.stdin.write('{}\r\n'.format(input_text).encode("utf8"))
    process.stdin.flush()
    # stdout, stderr = process.communicate('{}\n'.format(input_text).encode("utf8"))
    while True:
        line = process.stdout.readline().decode("utf8","ignore")
        if line == 'Input instruction: ':
            print(datetime.datetime.now(), 'run after: ', datetime.datetime.now())
            return '\n'.join(str_ret)
        print(datetime.datetime.now(), line)
        str_ret.append(line)
        time.sleep(2)